<style>
    .question-option label {
        color: black;
    }
</style>
<div class="row-fluid" id="PaperQuestionList" data-paperid="{$paperId}">
    <div class="span12">
        <div class="widget-box">
            <div class="widget-content nopadding" style="padding: 15px;">
                <div class="question-list-wrapper">
                    {volist name="List" id="vo"}
                    <div class="question-wrapper" data-id="{$vo.id}" key="key">
                        <div class="question-inner">
                            <p class="question-title">{$vo.name}</p>
                            {if condition="$vo.type eq 5"}
                            <p class="question-answer">关键词：{$vo.keyword}</p>
                            <p class="question-answer">重要关键词：{$vo.keyword_imp}</p>
                            {elseif condition="$vo.type eq 4"/}
                            <ul class="option">
                                {volist name="vo['answerList']" id="vo1" key="key1"}
                                <li class="selected"></li>
                                {/volist}
                            </ul>
                            {elseif condition="$vo.type eq 3"/}
                            <ul class="option">
                                {volist name="vo['optionsList']" id="vo1" key="key1"}
                                <li {if condition="in_array($key1, $vo.answerList) "}class="selected"{/if}>{$letter[$key1 - 1]}.{$vo1}</li>
                                {/volist}
                            </ul>
                            {else}
                            <ul class="option">
                                {volist name="vo['optionsList']" id="vo1" key="key1"}
                                    <li {if condition="$letter[$key1 - 1] eq $vo.answer1"}class="selected"{/if}>{$letter[$key1 - 1]}.{$vo1}</li>
                                {/volist}
                            </ul>
                            {/if}
                            <p class="question-answer">答案：{$vo.answer1}</p>
                            <p class="question-analysis">解析：{$vo.analysis}</p>
                            <div class="question-score-wrapper">
                                <input type="number" name="score" value="{$vo.score}" title="试题分数">分
                            </div>
                            <a class="edit" href="javascript:" data-id="{$vo.id}"><i class="fa fa-edit"></i>编辑</a>
                            <a class="remove" href="javascript:" data-id="{$vo.id}"><i class="fa fa-trash"></i>删除</a>
                            <a class="up" href="javascript:"><i class="fa fa-chevron-up"></i>上移</a>
                            <a class="down" href="javascript:"><i class="fa fa-chevron-down"></i>下移</a>
                        </div>
                    </div>
                    {/volist}
                </div>
                <div class="text-right">
                    <a id="addPaperQuestion" href="javascript:" style="margin-right: 10px;">新增试题</a>
                    <!--<a id="selectPaperQuestion" href="javascript:" style="margin-right: 10px;">选择试题</a>-->
                    <a id="savePaperQuestionList" class="btn btn-primary btn-save-title">保存</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    (function () {
        var questionListWrapper = $('.question-list-wrapper');

        // 选择题型
        // $(document).on('change', '.questionForm .question-type', function () {
        //     var val = $(this).val();
        //     if (val !== null) {
        //         $(this).siblings('.question-setting-wrapper').find('.question-type-pane.active').removeClass('active');
        //         $(this).siblings('.question-setting-wrapper').find('.question-type-pane[data-type="' + val + '"]').addClass('active');
        //     }
        // });

        // 判断题选择初始化
        $(document).on('click', '.questionForm .trueOrFalse', function () {
            $(this).siblings('input[type=radio]').trigger('click');
        });

        // 编辑试题
        questionListWrapper.on('click', '.question-wrapper a.edit', function (e) {
            e.preventDefault();
            var that = $(this);
            var id = that.data('id');
            $.post("{:url('paper/editPaperQuestion')}", {
                id: id
            }).then(function (html) {
                layer.open({
                    type: 1,
                    title: '编辑试题',
                    skin: false,
                    area: ['800px', '650px'],
                    content: html
                });
            });
            // var that = $(this);
            // var id = $(this).data('id');
            // var score = $(this).parent().find("input[name='score']").val();
            // $.ajax({
            //     url: "{:url('paper/editQuestion')}",
            //     type: 'post',
            //     data: {
            //         id: id,
            //     }
            // }).done(function (response) {
            //     if (response.status) {
            //         var questionWrapper = that.parent().parent();
            //         that.parent().hide();
            //         questionWrapper.append(questionEditTpl());
            //         that.parent().siblings('.questionForm').find('.question-type').val(response.data.type).trigger('change');
            //         var html = "<div class='question-title'>题目:<input type='text' value='" + response.data.title + "'></div>";
            //         // 试题内容
            //         switch (response.data.type) {
            //             case 1:
            //                 $.each(response.data.optionsList, function (index, item) {
            //                     html += '       <div class="question-option">';
            //                     html += '           <input type="radio" name="trueOrFalse" title="判断题选项"' + (response.data.answer == index + 1 ? 'checked' : '') + '>';
            //                     html += '           <label class="label trueOrFalse">' + item + '</label>';
            //                     html += '       </div>';
            //                     console.log(item);
            //                 });
            //                 break;
            //             case 2:
            //                 $.each(response.data.optionsList, function (index, item) {
            //                     html += '       <div class="question-option">';
            //                     html += '            <input type="radio" name="radio" title="单选题选项"' + (response.data.answer == index + 1 ? 'checked' : '') + '>';
            //                     html += '            <input type="text" title="单选题选项内容" value="' + item + '">';
            //                     html += '       </div>';
            //                 });
            //                 html += '       <a class="btn btn-primary add-option" href="javascript:"><i class="icon-plus"></i></a>';
            //                 break;
            //             case 3:
            //                 $.each(response.data.optionsList, function (index, item) {
            //                     html += '       <div class="question-option">';
            //                     html += '             <input type="checkbox" name="checkbox" title="复选题选项" ' + (response.data.answer.search(index + 1) != -1 ? 'checked' : '') + '>';
            //                     html += '             <input type="text" title="复选题选项内容" value="' + item + '">';
            //                     html += '       </div>';
            //                 });
            //                 html += '       <a class="btn btn-primary add-option" href="javascript:"><i class="icon-plus"></i></a>';
            //                 break;
            //             case 4:
            //                 $.each(response.data.answerList, function (index, item) {
            //                     html += '       <div class="question-option">';
            //                     html += '             <label class="label trueOrFalse">' + (index + 1) + '</label>';
            //                     html += '             <input type="text" title="填空题选项内容" value="' + item + '">';
            //                     html += '       </div>';
            //                 });
            //                 html += '       <a class="btn btn-primary add-option" href="javascript:"><i class="icon-plus"></i></a>';
            //                 break;
            //             case 5:
            //                 break;
            //             default:
            //                 break;
            //         }
            //         that.parent().siblings('.questionForm').find('.question-type-pane[data-type="' + response.data.type + '"]').html(html);
            //     } else {
            //         console.error('无数据');
            //     }
            // }).fail(function () {
            //     console.error('数据获取异常');
            // });
        });

        // 删除试题
        questionListWrapper.on('click', '.question-wrapper a.remove', function (e) {
            e.preventDefault();
            var id = $(this).data('id'),
                that = $(this);
            $.ajax({
                url: "{:url('Paper/deleteQuestions')}",
                type: 'post',
                data: {id: id},
            }).done(function (response) {
                layer.msg('删除成功');
                that.parent().parent().remove();
            }).fail(function () {
                console.error('请求失败！');
            });
        });

        // 上移试题
        questionListWrapper.on('click', '.question-wrapper a.up', function (e) {
            e.preventDefault();
            if ($(this).parent().parent().prevAll().length > 0) {
//                $(this).parent().prev().data('order', $(this).parent().data('order'));
//                $(this).parent().data('order', $(this).parent().data('order') - 1);
                $(this).parent().parent().prev().before($(this).parent().parent());
            }
        });

        // 下移试题
        questionListWrapper.on('click', '.question-wrapper a.down', function (e) {
            e.preventDefault();
            if ($(this).parent().parent().nextAll().length > 0) {
//                $(this).parent().next().data('order', $(this).parent().data('order'));
//                $(this).parent().data('order', $(this).parent().data('order') + 1);
                $(this).parent().parent().next().after($(this).parent().parent());
            }
        });

        // 保存试卷
        $('#savePaperQuestionList').on('click', function (e) {
            var selectors = $('.question-list-wrapper .question-wrapper');
            var paperId = $('#PaperQuestionList').data('paperid');
            var questions = [], totalScore = 0;
            if (selectors.length > 0) {
                $.each(selectors, function (index, item) {
                    var score = $(item).find('[name="score"]').val();
                    if(score <= 0) {
                        layer.msg('试题分数必须为数字且大于0');
                        return;
                    }
                    var question = {
                        id: $(item).data('id'),
                        score: score,
                        order: index
                    };
                    totalScore += parseInt(score);
                    questions.push(question);
                });

                var formData = {
                    id: paperId,
                    totalScore: totalScore,
                    questions: questions
                };

                $.post("{:url('paper/saveQuestions')}", {
                    formData: formData
                }).then(function (response) {
                    if(response.status) {
                        layer.closeAll();
                        layer.msg("保存成功！");
                    }else {
                        layer.msg(response.message);
                    }
                });
            } else {
                layer.msg('试卷试题不能少于1道！'); // 提示框
            }
        });

        // 获取试卷各试题排序及分值，并统计总分
        // function collectionPaperQuestionData() {
        //     var selectors = $('.question-list-wrapper .question-wrapper');
        //     var paperId = $('#PaperQuestionList').data('paperid');
        //     var questions = [], totalScore = 0;
        //     $.each(selectors, function (index, item) {
        //         var question = {
        //             id: $(item).data('id'),
        //             score: $(item).find('[name="score"]').val(),
        //             order: index
        //         };
        //         totalScore += $(item).find('[name="score"]').val();
        //         questions.push(question);
        //     });
        //
        //     return {
        //         id: paperId,
        //         totalScore: totalScore,
        //         questions: questions
        //     }
        // }

        // 获取编辑试题数据
        function collectQuestionContent(element) {
            var questionItem = {
                id: $(element).data('id'), // 试卷-试题id
                type: $(element).data('type'), // 试题类型
                title: $(element).find('.question-title > .text').text(), // 试题题目
                score: $(element).find('.score-text > .text').text(), // 试题分数
                options: "", // 试题选项内容（多项，用‘|||’隔开）
                answer: "" // 考生答案内容（多项，用‘|||’隔开）
            };
            var optionList = [], // 临时存放选项内容（多项）
                answerList = []; // 临时存放考生答案（多项）

            switch (questionItem.type) {
                case 1: // 判断题
                    questionItem.options = optionList.join('||');
                    questionItem.answer = $.trim($(element).find('[name="question' + questionItem.index + '"]:checked').val()) === undefined ? '' : $.trim($(element).find('[name="question' + questionItem.index + '"]:checked').val());
                    break;
                case 2: // 单选题
                    $.each($(element).find('[name="question' + questionItem.index + '"]'), function (index, item) {
                        optionList.push($(item).val());
                    });
                    questionItem.options = optionList.join('||');
                    questionItem.answer = $.trim($(element).find('[name="question' + questionItem.index + '"]:checked').val()) === undefined ? '' : $.trim($(element).find('[name="question' + questionItem.index + '"]:checked').val());
                    break;
                case 3: // 多选题
                    $.each($(element).find('[name="question' + questionItem.index + '"]'), function (index, item) {
                        optionList.push($.trim($(item).val()));
                    });
                    questionItem.options = optionList.join('||');
                    $.each($(element).find('[name="question' + questionItem.index + '"]:checked'), function (index, item) {
                        answerList.push($.trim($(item).val()));
                    });
                    questionItem.answer = answerList.join('||');
                    break;
                case 4: // 填空题
                    $.each($(element).find('[name="question' + questionItem.index + '"]'), function (index, item) {
                        answerList.push($.trim($(item).val()) === '' ? ' ' : $.trim($(item).val()));
                    });
                    questionItem.answer = answerList.join('||');
                    break;
                case 5: // 简答题
                    questionItem.answer = $.trim($(element).find('[name="question' + questionItem.index + '"]').val());
                    break;
            }
            return questionItem;
        }

        // 添加试卷-试题
        $('#PaperQuestionList').on('click', '#addPaperQuestion', function () {
            var paperId = $('#PaperQuestionList').data('paperid');
            var order = $('.question-wrapper').length;

            $.post("{:url('paper/addQuestion')}", {
                paper_id: paperId,
                order: order
            }).then(function (html) {
                layer.open({
                    type: 1,
                    title: '添加试题',
                    skin: false,
                    area: ['800px', '650px'],
                    content: html
                });
            });
        });

    })();
</script>